<template>
  <el-form ref="deptForm" label-width="120px">
    <el-form-item label="部门名称">
      <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门编码">
      <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门负责人">
      <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
        <el-option v-for="item in employees" :key="item.id" :value="item.username" :label="item.username" />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍">
      <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small">取消</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import { yuangongxingming } from '@/api/yuangongliebiao'
import { tianjiabumen, getDepartmentById, updateDepartmentById } from '@/api/zuzhiliebiao'
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      employees: []
    }
  },
  created() {
    this.yuangong()
    this.loadDepartmentDetail()
  },
  methods: {
    // 获取员工姓名
    async yuangong() {
      try {
        const res = await yuangongxingming()
        this.employees = res.data
      } catch (e) { console.log(e) }
    },

    // 数据回填
    async loadDepartmentDetail() {
      if (!this.isEdit) return // 趁早返回
      // 发请求
      const res = await getDepartmentById(this.id)
      // console.log(res)
      // 数据回填
      this.form = res.data
    },
    // 增加部门或者编辑部门
    async hSubmit() {
      try {
        let res = null
        if (this.isEdit) {
        // 根据isedit进行增加部门或者编辑部门
          res = await updateDepartmentById(this.form)
        } else {
          this.form.pid = this.id
          res = await tianjiabumen(this.form)
        }

        this.$message.success(res.message)
        // 4. 关闭 dialog
        // 5. 再次发请求获取最新的部门信息
        // 子传父: 触发父组件绑定的事件 success
        this.$emit('success')
      } catch (e) {
        this.$message.error(e.message)
      }
    }

  }
}
</script>

